#include "photomanager.h"

#include <QNetworkRequest>
#include <QNetworkReply>
#include <QDebug>

namespace ImageDownload {

PhotoManager* PhotoManager::m_instance = 0;

PhotoManager* PhotoManager::instance(QObject *parent)
{
    if (!m_instance) {
        m_instance = new PhotoManager(parent);
    }
    return m_instance;
}

PhotoManager::PhotoManager(QObject *parent) :
        QObject( parent )
{
    m_imageCache.setMaxCost(300);
}

PhotoManager::~PhotoManager()
{
    m_instance = 0;
}

void PhotoManager::imageGet(const QString &imageUrl)
{
    m_url = imageUrl;
    if (m_imageCache.contains(imageUrl)) {
        emit imageReadyForUrl(imageUrl, m_imageCache[imageUrl]);
        return;
    }

    QUrl url(imageUrl);
    QString host(url.host());
    QNetworkRequest request(url);

    if ( !m_connections.contains(host)) {
        m_connections.insert(host, new QNetworkAccessManager(this));
        connect(m_connections[host], SIGNAL(finished(QNetworkReply*)), this, SLOT(requestFinished(QNetworkReply*)));
    }

    m_connections[host]->get(request);
}

bool PhotoManager::contains(const QString &imageUrl) const
{
    return m_imageCache.contains(imageUrl);
}

QPixmap* PhotoManager::imageFromUrl(const QString &imageUrl) const
{
    return m_imageCache[imageUrl];
}

void PhotoManager::requestFinished(QNetworkReply *reply)
{
    int replyCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

    if (replyCode != 200){
        imageGet(m_url);
        return;
    }

    QPixmap *pixmap = new QPixmap;
    pixmap->loadFromData(reply->readAll());

    m_imageCache.insert(reply->url().toString(), pixmap);
    emit imageReadyForUrl(reply->url().toString(), pixmap);
}


/*! \class ImageDownload
    \brief A class for downlading images for Statuses.

    This is a class that provides interface for downloading user profile images
    for Statuses.
*/

/*! \fn ImageDownload::ImageDownload()
    A default constructor.
*/

/*! \fn void ImageDownload::imageGet( Entry *entry )
    This method invokes HttpConnection::prepareRequest() for a path
    given in \a entry, assigns allocated data to newly created
    ImageData instance and then issues QHttp::get().
    \param entry Entry for which the image will be downloaded.
*/

/*! \fn void ImageDownload::clearData()
    Forces clearing of temporary images store, gathered while updating timeline.
*/

/*! \fn void ImageDownload::imageReadyForUrl( const QString& path, QPixmap image )
    Emitted when the request is finished and the image is ready to be displayed.
    \param path The image's URL.
    \param image The downloaded image.
*/
}
